package com.pansoft.openplanet.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.FileDeleteUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.account.model.EthBean;
import com.pansoft.openplanet.account.util.EthAccountGenerator;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.LoginFlowManager;

import org.web3j.crypto.ECKeyPair;

import java.io.File;

import io.reactivex.disposables.Disposable;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 创建钱包
 * Created by will on 18-3-20.
 */

public class CreateWalletActivity extends TCBaseActivity implements View.OnClickListener {

    private String TAG = this.getClass().getSimpleName();
    //    private String pictureUrlPath = "";//头像在网络上的位置
//    private PictureAndCropManager pictureAndCropManager;//拍照裁剪
//    private ImageView ivAvatar;//头像框
//    private EditText etNickName;//账户名称
//    private CheckBox checkBox;//是否同意
    private Button tvCreateWallet;
    private Button tvResotreWallet;
    private String number = "";
    private ScrollView scrollView;
    public static final String LAST_ACTIVITY = "lastActivity";
    private TextView tvTopIntro;//创建您的基地账户/恢复您的基地账户
    private TextView tvMiddleIntro, tvBottomIntro;
    private TextView tvTitle;

    private String userName = "";
    //助记词
    private String mnemonic;
    //帐号
    private String address;
    //数据库
    private AccountDao accountDao;
    //密钥
    private ECKeyPair ecKeyPair;

    private File keyStoreFile;
    private String loginPwd = "";

//    private SelectAvatarDialog selectAvatarDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_activity_create_wallet);
        accountDao = new AccountDao(this);
        setEnableScreenShotListen(false);
        initView();
        initOther();
    }

    private void initOther() {
//        pictureAndCropManager = new PictureAndCropManager(this);


        if (getIntent().getExtras() != null && getIntent().getExtras().get("number") != null) {
            number = (String) getIntent().getExtras().get("number");
        }
        if (getIntent().getExtras() != null && getIntent().getExtras().get("userName") != null) {
            userName = (String) getIntent().getExtras().get("userName");
        }
        if (getIntent().hasExtra("loginPwd")) {
            loginPwd = getIntent().getStringExtra("loginPwd");
        }
        //当前是创建或者恢复状态
        EnvironmentVariable.setProperty(LoginFlowManager.getCreateWalletStateKey(number), "true");
//        selectAvatarDialog = new SelectAvatarDialog(this, pictureAndCropManager);

        //服务器钱包地址不为空  只允许恢复钱包
        //本地无钱包，服务器也无，创建和恢复都可以
//        if (!"".equals(EnvironmentVariable.getProperty("tc_ethAddress",""))){
//            tvCreateWallet.setVisibility(View.GONE);
//            tvTitle.setText("恢复基地账户");
//            tvTopIntro.setText("恢复您的基地账户");
//            tvMiddleIntro.setText(getResources().getString(R.string.restore_wallet_intro));
//            tvBottomIntro.setText("填写助记词请留意周边环境");
//        }

    }

    private void initView() {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.create_jidi_account);

//        etNickName = (EditText) findViewById(R.id.et_nick_name);
//        checkBox = (CheckBox) findViewById(R.id.checkBox);
//        checkBox.setChecked(true);
//        TextView tvTerms = (TextView) findViewById(R.id.tv_terms);
//        tvTerms.setOnClickListener(this);
//        ivAvatar = (ImageView) findViewById(R.id.iv_avatar);
//        ivAvatar.setOnClickListener(this);
        tvCreateWallet = (Button) findViewById(R.id.tv_create_wallet);
        tvCreateWallet.setOnClickListener(this);
        tvResotreWallet = (Button) findViewById(R.id.tv_restore_wallet);
        tvResotreWallet.setOnClickListener(this);
        scrollView = (ScrollView) findViewById(R.id.scrollview);
        tvTopIntro = (TextView) findViewById(R.id.tv_welcome);
        tvMiddleIntro = (TextView) findViewById(R.id.tv_wallet_intro);
        tvBottomIntro = (TextView) findViewById(R.id.tv_create_hint);
//        etNickName.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                scrollToShowSubmitBtn(scrollView);
//            }
//        });

        scrollToShowSubmitBtn(scrollView);
    }


    @Override
    public void onBackPressed() {
        //回到输入手机号界面
        try {
            Class class1 = Class.forName("com.efounder.activity.Login_withTitle");
            Intent intent = new Intent(this, class1);
            startActivity(intent);
            finish();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            finish();
        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        String lastActivity = "";
        if (getIntent().hasExtra(LAST_ACTIVITY)) {
            lastActivity = getIntent().getStringExtra(LAST_ACTIVITY);
        }

        if (id == R.id.iv_back) {
            onBackPressed();
//        } else if (id == R.id.tv_terms) {
            //条款
        } else if (id == R.id.tv_create_wallet) {
            //创建新账户
//            Intent intent = new Intent(CreateWalletActivity.this, CreateWalletConfirm.class);
//            intent.putExtra("userName", userName);
//            intent.putExtra("password", EnvironmentVariable.getPassword());
//            intent.putExtra("number", number);
////            intent.putExtra("avatar", pictureUrlPath);
//            intent.putExtra(LAST_ACTIVITY, lastActivity);
//            startActivity(intent);
            if (getIntent().hasExtra("localAddress")
                    && !getIntent().getStringExtra("localAddress").toLowerCase()
                    .equals(EnvironmentVariable.getProperty("tc_ethAddress", "").toLowerCase())) {
                generateWallet();
                return;

            }


            if (!"".equals(EnvironmentVariable.getProperty("tc_ethAddress", ""))) {
                new AlertDialog.Builder(CreateWalletActivity.this)
                        .setTitle(R.string.common_text_hint)
                        .setMessage(R.string.account_has_created)
                        .setPositiveButton(R.string.common_text_continue, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
//                        Intent intent = new Intent(CreateWalletConfirm.this, BackupWalletActivity.class);
                                generateWallet();
                            }
                        }).setNegativeButton(R.string.common_text_cancel, null)
                        .create().show();
            } else {
                generateWallet();
            }


        } else if (id == R.id.tv_restore_wallet) {
            //导入账户
            Intent intent = new Intent(CreateWalletActivity.this, RestoreWalletActivityTwo.class);
            intent.putExtra("userName", userName);
            intent.putExtra("number", number);
            intent.putExtra("avatar", "");
            intent.putExtra("loginPwd", loginPwd);
            intent.putExtra(LAST_ACTIVITY, lastActivity);
            startActivity(intent);

        }
    }


    @Override
    protected void onStop() {
        super.onStop();
//        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    private void generateWallet() {
        ecKeyPair = null;
        address = null;
        keyStoreFile = null;
        showLoading(R.string.open_planet_iscreateing);

        //keystore存放的路径
        final String path = TalkChainConstant.getDataFilePath(this) + File.separator + number;
        //文件夹不存在，创建文件夹
        final File file = new File(path);
        //清空文件夹
        if (file != null) {
            FileDeleteUtil.delete(file);
        }
        file.mkdirs();
        accountDao.deleteByCurentImuserId();
        Disposable disposable = EthAccountGenerator.createEthAccountAsync(path, new EthAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(EthBean ethBean) {
                dismissLoading();

                address = ethBean.getEthAddress();
                keyStoreFile = new File(ethBean.getKeyStoreFilePath());
                ecKeyPair = ethBean.getEcKeyPair();
                mnemonic = ethBean.getMnemonic();

                // saveAccount();
                //保存到数据库
                Account account = new Account(address, "", "");
                account.setFileName(keyStoreFile.getAbsolutePath());
                account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                account.setPublicKey(ethBean.getEcKeyPair().getPublicKey().toString());
                account.setMaster(true);
                account.setCurrentShow(true);
                account.setEnable(false);
                account.setMainAccoutAddress(ethBean.getEthAddress());
                accountDao.insertOrReplace(account);
                //显示成功对话框
                showSuccessAlert();
            }

            @Override
            public void generatorFail() {
                dismissLoading();
                showFailAlert(null);
            }
        });
        if (disposable != null) {
            addDisposable(disposable);
        }

    }


    private void showFailAlert(String message) {
        if (message == null)
            message = ResStringUtil.getString(R.string.open_planet_create_fail_please_retry);
        new AlertDialog.Builder(CreateWalletActivity.this)
                .setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        generateWallet();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, null)
                .create()
                .show();
    }

    private void showSuccessAlert() {
        new AlertDialog.Builder(CreateWalletActivity.this)
                .setTitle(R.string.common_text_hint)
                .setMessage(R.string.openplanet_jidi_create_success)
                .setPositiveButton(R.string.openplanet_goback, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        Intent intent = new Intent(CreateWalletConfirm.this, BackupWalletActivity.class);
                        Intent intent = new Intent(CreateWalletActivity.this, BackupTokenHelperActivity.class);

                        intent.putExtra("userName", userName);
                        intent.putExtra("number", number);
                        intent.putExtra("mnemonic", mnemonic);//助记词
                        intent.putExtra("address", address);
                        intent.putExtra("loginPwd", loginPwd);

                        intent.putExtra("ethPublicKey", ecKeyPair.getPublicKey().toString());
                        intent.putExtra("ethPrivateKey", ecKeyPair.getPrivateKey().toString());
                        intent.putExtra(CreateWalletActivity.LAST_ACTIVITY, getIntent().getStringExtra(CreateWalletActivity.LAST_ACTIVITY));
                        startActivity(intent);
                    }
                })
                .create().show();
    }


    /**
     * 使滚动条滚动至指定位置（垂直滚动）
     *
     * @param scrollView 要滚动的ScrollView
     * @param to         滚动到的位置
     */
    protected void scrollVertical(final ScrollView scrollView, final int to) {
        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, to);
            }
        }, 100);
    }

    /**
     * 使ScrollView滚动至底部，显示Submit按钮
     *
     * @param scrollView 要滚动的scrollView
     */
    protected void scrollToShowSubmitBtn(final ScrollView scrollView) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollVertical(scrollView, scrollView.getHeight());
            }
        }, 200);
    }

}
